define [
	'jquery'
	'template'
	'lib/jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->
	S = {}
	editDoc = $instance = {}
	ctrlFlag = repeat = false

	toggleFlag = (a)-> 
		ctrlFlag = not ctrlFlag
		if a? then ctrlFlag = off

	# Save Doc function
	saveDoc = (newVal) ->
		# Identify which property of the document to change
		prop = $instance.attr('name')

		# Change the property in the editDoc object in memory
		editDoc[prop] = newVal

		$.couch.db('vcn-members').saveDoc editDoc, 
			success: (data) ->
				toggleFlag(off)
				$instance.empty().text newVal
				editDoc._rev = data.rev
				if data['ok'] then msg "Saved!", "green" else msg "Error!", "red"
			error: (e) ->
				if e is 409 and not repeated
					$.couch.db('vcn-members').openDoc donor_id,
						success: (doc) ->
							editDoc._rev = doc._rev
							saveDoc(newVal)
							repeated = true
						error: (e) ->
							$instance.empty().text oldVal
							msg "Error! #{e}", "red"
	
	# Message display function
	msg = (text, color) ->
		$('.msg').show()
			.text("#{text}")
			.css(
				"color": color
				"z-index" : "-1"
				"position": "absolute"
				"top" : $instance.position().top + ($instance.innerHeight() / 2) - $('.msg').innerHeight() / 2
				"left" : $instance.position().left + $instance.innerWidth() + 20
				)
			.delay(2500)
			.fadeOut(500)

	$.fn.mb_donor_detail = (SamCtx) ->

		ins = @
		$this = $(@)
		S = SamCtx
		$editTpl = $('<input type="text" id="editor"/>')
		$editBtn = $('<input type="button" class="ok" value="OK"><input type="button" class="cancel" value="Cancel">')
		$override = $('<input type="checkbox" name="override"><font>Force Save</font>')
		donor_id = ""
		$tpl = $this.find('.tpl').hide()

		unless @mb_plugin()
			@mb_plugin 'donor_detail'
			$this.append $('<font class="msg">')
			$tpl.find('tr').each ()-> $('td:eq(0)', @).addClass('labels')

			$.subscribe 'mb.donor', (e, arg) ->
				toggleFlag(off)
				donor_id = arg['donor_id']
				$detail = $tpl.clone().show()

				$.couch.db('vcn-members').openDoc donor_id,
					success: (data) ->
						editDoc = data
						if not data.org then $detail.find('.org').remove() else $detail.find('.ind').remove()
						content = S.content $detail, data
						$this.find('#detail .content').empty().append content
					error: (status) ->
						console.log(status)
						$.publish 'mb.error', 'Document is not open'


			# Event handling for creation of the input box, ok button, and a cancel button
			$('.content').on "click", "td.editable", ->
				repeated = false

				# The ctrlFlag is a plugin flag (boolean var) that determines if a control is already
				# existing. This restricts to only one field to become edit mode at any given time
				# Therefore, if the flag is true, then return out of this event handler
				if not ctrlFlag then toggleFlag() else return

				# Local minimized global variables
				$instance = $(@)
				oldVal = $(@).text()

				# Clone the input text box and set its name to the name of the cell as well
				# as the value with the current text inside the td cell
				$edit = $editTpl.clone().attr
					"name"	: $(@).attr "name"
					"value"	: oldVal
					"z-index" : 1

				# Insert textbox and buttons into form and select the textbox
				$(@).empty().append ($form = $('<form>').append($edit).append $editBtn.clone())
				($editor = $this.find('#editor')).focus()

				# Event handling for cancel button of editor
				$(@).find('input.cancel').click ()->
					toggleFlag(off)
					$instance.empty().text oldVal

				# Enter key refreshes the page despite a focus on the input box
				# Therefore, define a key hook to catch "enter" key pressed with the input box
				# and invoke a click on the "Ok" button. "Esc" keypress invokes the "cancel" button
				$(@).on 'keydown', '#editor', (e)->
					if e.keyCode is 13
						$form.find('input.ok').click()
						return false
					if e.keyCode is 27
						$form.find('input.cancel').click()
						return false
					return

				# Event handling for OK button of editor
				$('input.ok', @).on 'click', ->
					newVal = $editor.val()

					# Create override "Force Save" checkbox
					createOverride = ()->
						return if $form.is(":has(input:checkbox)")
						$form.append $override.clone()

					# Check if override checkbox is checked, if checked then just save the doc
					if $instance.find('input:checkbox').is(":checked")
						saveDoc(newVal)
						return

					switch $('#editor', ins).attr('name')
						when "last_name", "first_name"
							break if $('.content table', ins).is(":has(.org)")
							if $editor.val().length is 0
								$.publish "mb.msg", {msg: "Name field cannot be empty.", type: "error"}
								return false
						# If editing postal_code check postal code format
						when "postal_code"
							if not $editor.val().isPostal(0)
								createOverride()
								$.publish "mb.msg", {msg: "Postal Code is not valid.", type: "error"}
								return false 
						# If editing phone numbers check phone number format
						when "tel_home", "tel_work", "tel_contact", "tel_fax"
							if not (phone = $editor.val()).isPhone(0)
								# If phone number has 10 digits, then format the phone number ourselves
								if phone.isPhone().length is 10
									$editor.val phone.isPhone(1)
									newVal = $editor.val()
								else
									createOverride()
									$.publish "mb.msg", {msg: "Phone Number is in an incorrect format (###) ###-####", type: "error"}
									return false

					# If the old and new values are identical, then just don't save anything
					if oldVal is newVal
						$instance.find('input.cancel').click()
						return false

					saveDoc(newVal)

					return # Return false for submit button
				return

	return @









